package pl.un4giv3n.mightvsmagic.action;

import javax.mail.NoSuchProviderException;
import javax.persistence.EntityManager;

import pl.un4giv3n.mightvsmagic.entity.Clan;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.utils.ClanUtil;
import pl.un4giv3n.mightvsmagic.utils.MailSender;
import pl.un4giv3n.mightvsmagic.utils.UserUtil;

/**
 * @author andrzejewskia
 * delete player
 */
public class DeleteAccountAction extends ProfilePageAction {

	private static final long serialVersionUID = 1L;
	private String password;
	/**
	 * session user to be deleted
	 */
	private User user;

	/* (non-Javadoc)
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();	
			return LOGIN;
		}
		password = UserUtil.encyptPassword(password.trim());
		if(!user.getPassword().equals(password)){
			addActionError("Niepoprawne hasło");
			entityManager.close();
			return INPUT;
		}
		entityManager.getTransaction().begin();
		user.setBlocked(true);
		user.setBlockReason("Kasacja przez gracza");
		Clan clan = user.getClan();
		if(clan != null){
			clan.getUsers().remove(user);
			user.setClan(null);
			user.setClanAcceptancePending(false);
			user.setClanAdmin(false);
			user.setClanMod(false);
			if(clan.getUsers().isEmpty()){
				ClanUtil.endClanWars(clan.getId(), entityManager);
				entityManager.remove(clan);
			}
		}
		entityManager.merge(user);
		entityManager.flush();
		entityManager.getTransaction().commit();
		entityManager.close();
		getSession().put(USER_ID, null);
		try {
			MailSender.send(user.getEmail(), MailSender.DELETE_USER_SUBJECT, MailSender.getDeleteUserMessage(user, user.getId()+""));
		} catch (NoSuchProviderException e) {
			LOG.error(e.getMessage(),e);
			addActionError("Błąd wysyłania wiadomości e-mail dotyczącej rejestracji!");
			return INPUT;
		}
		return SUCCESS;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
